<?php
/**
 * Created by PhpStorm.
 * User: wangjie
 * Date: 2020/8/21
 * Time: 16:03
 */
namespace App\Api\Controllers\MeiTuanPeiSong;


use App\Models\MeituanpsConfigs;
use App\Models\MeituanpsOrders;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class AddController extends BaseController
{

    //订单创建(门店方式)
    public function orderCreateByShop(Request $request)
    {
        $token = $this->parseToken();
        $outer_order_source_desc = $request->get('outerOrderSourceDesc', '');
        $shop_id = $request->get('storeId', '');
        $delivery_service_code = $request->get('deliveryServiceCode', '');
        $receiver_name = $request->get('receiverName', '');
        $receiver_address = $request->get('receiverAddress', '');
        $receiver_phone = $request->get('receiverPhone', '');
        $receiver_lng = $request->get('receiverLng', '');
        $receiver_lat = $request->get('receiverLat', '');
        $goods_value = $request->get('goodsValue', '');
        $goods_weight = $request->get('goodsWeight', '');
        $outer_order_source_no = $request->get('outerOrderSourceNo', '');
        $coordinate_type = $request->get('coordinateType', '');
        $goods_height = $request->get('goodsHeight', '');
        $goods_width = $request->get('goodsWidth', '');
        $goods_length = $request->get('goodsLength', '');
        $goods_detail = $request->get('goodsDetail', '');
        $goods_pickup_info = $request->get('goodsPickupInfo', '');
        $goods_delivery_info = $request->get('goodsDeliveryInfo', '');
        $expected_pickup_time = $request->get('expectedPickupTime', '');
        $expected_delivery_time = $request->get('expectedDeliveryTime', '');
        $order_type = $request->get('orderType', '0');
        $poi_seq = $request->get('poiSeq', '');
        $note = $request->get('note', '');
        $cash_on_delivery = $request->get('cashOnDelivery', '');
        $cash_on_pickup = $request->get('cashOnPickup', '');
        $invoice_title = $request->get('invoiceTitle', '');

        $obj = MeituanpsConfigs::where('store_id', $shop_id)
            ->first();
        if (!$obj || empty($obj->appkey) || empty($obj->secret)) {
            return json_encode([
                'status' => '2',
                'message' => '美团配送参数未配置'
            ]);
        }

        $secret = $obj->secret;

        $delivery_id = $this->createDeliveryId(20); //
        $order_id = $this->createOrderId(); //

        try {
            $requestData = [
                'delivery_id' => $delivery_id, //即配送活动标识,由外部系统生成,不同order_id应对应不同的delivery_id,若因美团系统故障导致发单接口失败,可利用相同的delivery_id重新发单,系统视为同一次配送活动,若更换delivery_id,则系统视为两次独立配送活动
                'order_id' => $order_id, //订单id,即该订单在合作方系统中的id,最长不超过32个字符.注：目前若某一订单正在配送中(状态不为取消),再次发送同一订单(order_id相同)将返回同一mt_peisong_id
                'outer_order_source_desc' => $outer_order_source_desc, //订单来源:101-美团(外卖&闪购);102-饿了么;103-京东到家;201-商家web网站;202-商家小程序-微信;203-商家小程序-支付宝;204-商家APP;205.商家热线;其他请直接填写中文字符串,最长不超过20个字符,非[其他]需传代码
                'shop_id' => $shop_id, //取货门店id,即合作方向美团提供的门店id
                'delivery_service_code' => $delivery_service_code, //配送服务代码:飞速达-4002;快速达-4011;及时达-4012;集中送-4013
                'receiver_name' => $receiver_name, //收件人名称,最长不超过256个字符
                'receiver_address' => $receiver_address, //收件人地址,最长不超过512个字符
                'receiver_phone' => $receiver_phone, //收件人电话,最长不超过64个字符
                'receiver_lng' => $receiver_lng, //收件人经度(火星坐标或百度坐标,和 coordinate_type 字段配合使用),坐标 * (10的六次方),如 116398419
                'receiver_lat' => $receiver_lat, //收件人纬度(火星坐标或百度坐标,和 coordinate_type 字段配合使用),坐标 * (10的六次方),如 39985005
                'goods_value' => number_format($goods_value, 2), //货物价格,单位为元,精确到小数点后两位(如果小数点后位数多于两位,则四舍五入保留两位小数),范围为0-5000
                'goods_weight' => number_format($goods_weight, 2) //货物重量,单位为kg,精确到小数点后两位(如果小数点后位数多于两位,则四舍五入保留两位小数),范围为0-50
            ];
            if ($outer_order_source_no) $requestData['outer_order_source_no'] = $outer_order_source_no; //原平台订单号,如订单来源为美团,该字段必填,且为美团平台生成的订单号,最长不超过32个字符
            if ($coordinate_type) $requestData['coordinate_type'] = $coordinate_type; //坐标类型:0-火星坐标(高德,腾讯地图均采用火星坐标);1-百度坐标 (默认值为0)
            if ($goods_height) $requestData['goods_height'] = number_format($goods_height, 2); //货物高度,单位为cm,精确到小数点后两位(如果小数点后位数多于两位,则四舍五入保留两位小数),范围为0-45
            if ($goods_width) $requestData['goods_width'] = number_format($goods_width, 2); //货物宽度,单位为cm,精确到小数点后两位(如果小数点后位数多于两位,则四舍五入保留两位小数),范围为0-50
            if ($goods_length) $requestData['goods_length'] = number_format($goods_length, 2); //货物长度,单位为cm,精确到小数点后两位(如果小数点后位数多于两位,则四舍五入保留两位小数),范围为0-65
            if ($goods_detail) $requestData['goods_detail'] = $goods_detail; //货物详情,最长不超过10240个字符,内容为JSON格式,示例如下：{"goods":[{"goodCount": 1,"goodName": "货品名称","goodPrice": 9.99,"goodUnit": "个"}]}goods对应货物列表;goodCount表示货物数量,int类型,必填且必须大于0;goodName表示货品名称,String类型,必填且不能为空;goodPrice表示货品单价,double类型,选填,数值不小于0,精确到小数点后两位(如果小数点后位数多于两位,则四舍五入保留两位小数);goodUnit表示货品单位,String类型,选填,最长不超过20个字符。强烈建议提供,方便骑手在取货时确认货品信息
            if ($goods_pickup_info) $requestData['goods_pickup_info'] = $goods_pickup_info; //货物取货信息,用于骑手到店取货,最长不超过100个字符
            if ($goods_delivery_info) $requestData['goods_delivery_info'] = $goods_delivery_info; //货物交付信息,最长不超过100个字符
            if ($expected_pickup_time) $requestData['expected_pickup_time'] = strtotime($expected_pickup_time); //期望取货时间,时区为GMT+8,当前距离Epoch(1970年1月1日) 以秒计算的时间,即unix-timestamp
            if ($expected_delivery_time) $requestData['expected_delivery_time'] = strtotime($expected_delivery_time); //期望送达时间,时区为GMT+8,当前距离Epoch（1970年1月1日) 以秒计算的时间,即unix-timestamp.即时单(除当天送)：否.预约单：是.期望送达时间,时区为GMT+8,当前距离Epoch(1970年1月1日) 以秒计算的时间,即unix-timestamp.即时单：以发单时间 + 服务包时效作为期望送达时间(当天送服务包需客户指定期望送达时间).预约单：以客户传参数据为准(预约时间必须大于当前下单时间+服务包时效+3分钟)
            if ($order_type) $requestData['order_type'] = $order_type; //订单类型,默认为0.0: 即时单(尽快送达,限当日订单).1: 预约单
            if ($poi_seq) $requestData['poi_seq'] = $poi_seq; //门店订单流水号,建议提供,方便骑手门店取货,最长不超过32个字符
            if ($note) $requestData['note'] = $note; //备注,最长不超过200个字符
            if ($cash_on_delivery) $requestData['cash_on_delivery'] = $cash_on_delivery; //骑手应付金额,单位为元,精确到分【预留字段】
            if ($cash_on_pickup) $requestData['cash_on_pickup'] = $cash_on_pickup; //骑手应收金额,单位为元,精确到分【预留字段】
            if ($invoice_title) $requestData['invoice_title'] = $invoice_title; //发票抬头,最长不超过256个字符【预留字段】

            //资料入库
            $tableObj = MeituanpsOrders::create($requestData);
            if (!$tableObj) {
                return json_encode([
                    'status' => '2',
                    'message' => '写入美团配送订单表失败'
                ]);
            }

            Log::info('美团配送-订单创建(门店方式)');
            Log::info($requestData);
            $res = $this->http_post($this->order_create_by_shop, $requestData, $secret);
            Log::info($res);

            //成功,更新美团配送订单表
            if ($res['status'] == '1') {
                $result = MeituanpsOrders::where('id', $tableObj)->update([
                    'mt_peisong_id' => $res['data']['mt_peisong_id']
                ]);
                if (!$result) {
                    return json_encode([
                        'status' => '2',
                        'message' => '更新美团配送内部订单id失败'
                    ]);
                }
            }

            return json_encode($res);
        } catch (\Exception $ex) {
            return json_encode([
                'status' => '-1',
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine()
            ]);
        }
    }


    //订单创建(送货分拣方式)
    public function orderCreateByCoordinates(Request $request)
    {
        $token = $this->parseToken();
        $shop_id = $request->get('storeId', '');
        $outer_order_source_desc = $request->get('outerOrderSourceDesc', '');
        $delivery_service_code = $request->get('deliveryServiceCode', '');
        $pick_up_type = $request->get('pickUpType', '1');
        $receiver_name = $request->get('receiverName', '');
        $receiver_phone = $request->get('receiverPhone', '');
        $receiver_province = $request->get('receiverProvince', '');
        $receiver_city = $request->get('receiverCity', '');
        $receiver_country = $request->get('receiverCountry', '');
        $receiver_detail_address = $request->get('receiverDetailAddress', '');
        $receiver_lng = $request->get('receiverLng', '');
        $receiver_lat = $request->get('receiverLat', '');
        $goods_value = $request->get('goodsValue', '');
        $goods_weight = $request->get('goodsWeight', '');
        $expected_delivery_time = $request->get('expectedDeliveryTime', '');
        $order_type = $request->get('orderType', '1');
        $outer_order_source_no = $request->get('outerOrderSourceNo', '');
        $receiver_town = $request->get('receiverTown', '');
        $coordinate_type = $request->get('coordinateType', '0');
        $goods_height = $request->get('goodsHeight', '');
        $goods_width = $request->get('goodsWidth', '');
        $goods_length = $request->get('goodsLength', '');
        $goods_detail = $request->get('goodsDetail', '');
        $goods_pickup_info = $request->get('goodsPickupInfo', '');
        $goods_delivery_info = $request->get('goodsDeliveryInfo', '');
        $expected_pickup_time = $request->get('expectedPickupTime', '');
        $poi_seq = $request->get('poiSeq', '');
        $note = $request->get('note', '');

        $obj = MeituanpsConfigs::where('store_id', $shop_id)
            ->first();
        if (!$obj || empty($obj->appkey) || empty($obj->secret)) {
            return json_encode([
                'status' => '2',
                'message' => '美团配送参数未配置'
            ]);
        }

        $secret = $obj->secret;

        $delivery_id = $this->createDeliveryId(20); //
        $order_id = $this->createOrderId(); //

        try {
            $requestData = [
                'delivery_id' => $delivery_id, //即配送活动标识,由外部系统生成,不同order_id应对应不同的delivery_id,若因美团系统故障导致发单接口失败,可利用相同的delivery_id重新发单,系统视为同一次配送活动,若更换delivery_id,则系统视为两次独立配送活动
                'order_id' => $order_id, //订单id,即该订单在合作方系统中的id,最长不超过32个字符.注：目前若某一订单正在配送中(状态不为取消),再次发送同一订单(order_id相同)将返回同一mt_peisong_id
                'outer_order_source_desc' => $outer_order_source_desc, //订单来源:101-美团(外卖&闪购);102-饿了么;103-京东到家;201-商家web网站;202-商家小程序-微信;203-商家小程序-支付宝;204-商家APP;205.商家热线;其他请直接填写中文字符串,最长不超过20个字符,非[其他]需传代码
                'delivery_service_code' => $delivery_service_code, //配送服务代码:飞速达-4002;快速达-4011;及时达-4012;集中送-4013
                'pick_up_type' => $pick_up_type, //货物取货类型,目前只支持1(1-客户配送至站点;2-美团自取)
                'receiver_name' => $receiver_name, //收件人名称,最长不超过256个字符
                'receiver_phone' => $receiver_phone, //收件人电话,最长不超过64个字符
                'receiver_province' => $receiver_province, //收件人地址省,如上海市,江苏省,最长不超过10个字符
                'receiver_city' => $receiver_city, //收件人地址市,如上海市,南京市,最长不超过10个字符
                'receiver_country' => $receiver_country, //收件人地址区县,如静安区,最长不超过10个字符
                'receiver_detail_address' => $receiver_detail_address, //收件人地址详情,如永兴路365号,最长不超过100个字符
                'receiver_lng' => $receiver_lng, //收件人经度(火星坐标或百度坐标,和 coordinate_type 字段配合使用),坐标 * (10的六次方),如 116398419
                'receiver_lat' => $receiver_lat, //收件人纬度(火星坐标或百度坐标,和 coordinate_type 字段配合使用),坐标 * (10的六次方),如 39985005
                'goods_value' => number_format($goods_value, 2), //货物价格,单位为元,精确到小数点后两位(如果小数点后位数多于两位,则四舍五入保留两位小数),范围为0-5000
                'goods_weight' => number_format($goods_weight, 2), //货物重量,单位为kg,精确到小数点后两位(如果小数点后位数多于两位,则四舍五入保留两位小数),范围为0-50
                'expected_delivery_time' => strtotime($expected_delivery_time), //期望送达时间,时区为GMT+8,当前距离Epoch（1970年1月1日) 以秒计算的时间,即unix-timestamp
                'order_type' => $order_type //订单类型,目前只支持预约单.0-及时单(尽快送达,限当日订单);1-预约单
            ];
            if ($outer_order_source_no) $requestData['outer_order_source_no'] = $outer_order_source_no; //原平台订单号,如订单来源为美团,该字段必填,且为美团平台生成的订单号,最长不超过32个字符
            if ($receiver_town) $requestData['receiver_town'] = $receiver_town; //收件人地址街道,如宝山路街道,最长不超过30个字符
            if ($coordinate_type) $requestData['coordinate_type'] = $coordinate_type; //坐标类型:0-火星坐标(高德,腾讯地图均采用火星坐标);1-百度坐标 (默认值为0)
            if ($goods_height) $requestData['goods_height'] = number_format($goods_height, 2); //货物高度,单位为cm,精确到小数点后两位(如果小数点后位数多于两位,则四舍五入保留两位小数),范围为0-45
            if ($goods_width) $requestData['goods_width'] = number_format($goods_width, 2); //货物宽度,单位为cm,精确到小数点后两位(如果小数点后位数多于两位,则四舍五入保留两位小数),范围为0-50
            if ($goods_length) $requestData['goods_length'] = number_format($goods_length, 2); //货物长度,单位为cm,精确到小数点后两位(如果小数点后位数多于两位,则四舍五入保留两位小数),范围为0-65
            if ($goods_detail) $requestData['goods_detail'] = $goods_detail; //货物详情,最长不超过10240个字符,内容为JSON格式,示例如下:{"goods":[{"goodCount": 1,"goodName": "货品名称","goodPrice": 9.99,"goodUnit": "个"}]}goods对应货物列表;goodCount表示货物数量,int类型,必填且必须大于0;goodName表示货品名称,String类型,必填且不能为空;goodPrice表示货品单价,double类型,选填,数值不小于0,精确到小数点后两位（如果小数点后位数多于两位,则四舍五入保留两位小数）;goodUnit表示货品单位,String类型,选填,最长不超过20个字符。强烈建议提供,方便骑手在取货时确认货品信息
            if ($goods_pickup_info) $requestData['goods_pickup_info'] = $goods_pickup_info; //货物取货信息,用于骑手到店取货,最长不超过100个字符
            if ($goods_delivery_info) $requestData['goods_delivery_info'] = $goods_delivery_info; //货物交付信息,最长不超过100个字符
            if ($expected_pickup_time) $requestData['expected_pickup_time'] = strtotime($expected_pickup_time); //期望取货时间,时区为GMT+8,当前距离Epoch（1970年1月1日) 以秒计算的时间,即unix-timestamp
            if ($poi_seq) $requestData['poi_seq'] = $poi_seq; //门店订单流水号,建议提供,方便骑手门店取货,最长不超过32个字符
            if ($note) $requestData['note'] = $note; //备注,最长不超过200个字符


            //资料入库
            $tableObj = MeituanpsOrders::create($requestData);
            if (!$tableObj) {
                return json_encode([
                    'status' => '2',
                    'message' => '写入美团配送订单表失败'
                ]);
            }

            Log::info('美团配送-订单创建(送货分拣方式)');
            Log::info($requestData);
            $res = $this->http_post($this->order_create_by_coordinates, $requestData, $secret);
            Log::info($res);

            //成功,更新美团配送订单表
            if ($res['status'] == '1') {
                $result = MeituanpsOrders::where('id', $tableObj)->update([
                    'mt_peisong_id' => $res['data']['mt_peisong_id'],
                    'road_area' => $res['data']['road_area'],
                    'destination_id' => $res['data']['destination_id']
                ]);
                if (!$result) {
                    return json_encode([
                        'status' => '2',
                        'message' => '更新美团配送内部订单id失败'
                    ]);
                }
            }

            return json_encode($res);
        } catch (\Exception $ex) {
            return json_encode([
                'status' => '-1',
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine()
            ]);
        }
    }


    //订单id,即该订单在合作方系统中的id,最长不超过32个字符
    private function createOrderId()
    {
        $order_id = 'mt_ps' . date('YmdHis', time()) . substr(microtime(), 2, 6) . sprintf('%03d', rand(0, 999));
        //mt_ps20200822142107320365404
        $result = MeituanpsOrders::where('order_id', $order_id)->first();
        if ($result) $this->createOrderId();

        return $order_id;
    }


    //即配送活动标识,由外部系统生成
    protected function createDeliveryId($len)
    {
        $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
        $string = time();
        for (; $len >= 1; $len--) {
            $position = rand()%strlen($chars);
            $position2 = rand()%strlen($string);
            $string = substr_replace($string, substr($chars, $position, 1), $position2, 0);
        }

        $isExit = MeituanpsOrders::where('delivery_id', $string)->first();
        if ($isExit) $this->createDeliveryId(20);

        return $string;
    }


}
